﻿using DapperExtensions;
using DapperExtensions.Sql;
using DotNet.Http.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;

namespace FXPushService
{
    public class DataFetcher
    {
        public class ApiResult
        {
            public bool success { get; set; }

            public string msg { get; set; }

            public object data { get; set; }
        }
        Model1 _db = new Model1();

        PropertyInfo[] _riverInfoCache = null;
        PropertyInfo[] _dayrainInfoCache = null;
        PropertyInfo[] _resrviorInfoCache = null;

        public DataFetcher()
        {
            _riverInfoCache = typeof(river).GetProperties();
            _dayrainInfoCache = typeof(dayrain).GetProperties();
            _resrviorInfoCache = typeof(reservior).GetProperties(); 
        }

        IDbConnection GetDBConn()
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
            conn.Open();
            return conn;
        }
        /// <summary>  
        /// 批量插入功能  
        /// </summary>  
        public void InsertBatch<T>(IDbConnection conn, IEnumerable<T> entityList, IDbTransaction transaction = null) where T : class
        {
            var tblName = string.Format("dbo.{0}", typeof(T).Name);
            var tran = (SqlTransaction)transaction;
            using (var bulkCopy = new SqlBulkCopy(conn as SqlConnection, SqlBulkCopyOptions.TableLock, tran))
            {
                bulkCopy.BatchSize = entityList.Count();
                bulkCopy.DestinationTableName = tblName;
                var table = new DataTable();
                DapperExtensions.Sql.ISqlGenerator sqlGenerator = new SqlGeneratorImpl(new DapperExtensionsConfiguration());
                var classMap = sqlGenerator.Configuration.GetMap<T>();
                var props = classMap.Properties.Where(x => x.Ignored == false).ToArray();
                foreach (var propertyInfo in props)
                {
                    bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
                    table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyInfo.PropertyType) ?? propertyInfo.PropertyInfo.PropertyType);
                }
                var values = new object[props.Count()];
                foreach (var itemm in entityList)
                {
                    for (var i = 0; i < values.Length; i++)
                    {
                        values[i] = props[i].PropertyInfo.GetValue(itemm, null);
                    }
                    table.Rows.Add(values);
                }
                bulkCopy.WriteToServer(table);
            }
        }

        public ApiResult GetRiver()
        {
            ApiResult result = new ApiResult();
            HttpResponseParameter responseParameter1 = HttpUtil.Excute(new HttpRequestParameter
            {
                Url = "http://10.21.5.211:8080/lnflood/app/hydro/riverinfo",
                IsPost = false,
                Encoding = Encoding.UTF8 
            });


            result.success = true;
            try
            {
                var resarray = JsonConvert.DeserializeObject<List<river>>(responseParameter1.Body);
                var temp = resarray.Where(o =>
                {
                    if (string.IsNullOrEmpty(o.addvcd)) return false;
                    return o.addvcd.StartsWith("2111");
                });

              
                var conn = GetDBConn();
             
                //InsertBatch<river>(conn, temp.ToList());
                foreach (var t in temp)
                {

                    //int count = Convert.ToInt32(Dapper.SqlMapper.ExecuteScalar(conn, "select count(*) from river where stcd='" + t.stcd + "'"));
                    int count = _db.river.Count(o => o.stcd == t.stcd);
                    if (count == 0)
                    {
                        _db.river.Add(t);
                        
                    }
                    else
                    {
                        //update
                        var triver = _db.river.Single(r => r.stcd == t.stcd);
                        foreach (var p in _riverInfoCache)
                        {
                            if (p.Name == "id") continue;
                            if (p.GetValue(t, null) != p.GetValue(triver, null))
                                p.SetValue(triver,p.GetValue(t, null),null);
                        }
                       


                    }
                }
                _db.SaveChanges();

            }
            catch (Exception ex)
            {
                result.success = false;
                Console.WriteLine(ex.Message);
            }

            return result;
        }

        public ApiResult GetResinfo()
        {
            ApiResult result = new ApiResult();
            HttpResponseParameter responseParameter1 = HttpUtil.Excute(new HttpRequestParameter
            {
                Url = "http://10.21.5.211:8080/lnflood/app/hydro/resinfo",
                IsPost = false,
                Encoding = Encoding.UTF8

            });
            result.success = true;
            try
            {
                var resarray = JsonConvert.DeserializeObject<resinfo>(responseParameter1.Body);
                var temp = resarray.items.Where(o =>
                {

                    if (string.IsNullOrEmpty(o.addvcd)) return false;
                    return o.addvcd.StartsWith("2111");
                });
                

                var conn = GetDBConn();

                //InsertBatch<reservior>(conn, temp.ToList());
                foreach (var t in temp)
                {
                    //int count = Convert.ToInt32(Dapper.SqlMapper.ExecuteScalar(conn, "select count(*) from reservior where stcd='" + t.stcd + "'"));

                    int count = _db.reservior.Count(o => o.stcd == t.stcd);
                    if (count == 0)
                    {
                        _db.reservior.Add(t);

                    }
                    else
                    {
                        //update
                      
                        var treservior = _db.reservior.Single(r => r.stcd == t.stcd);
                        foreach (var p in _resrviorInfoCache)
                        {
                            if (p.Name == "id") continue;
                            if (p.GetValue(t, null) != p.GetValue(treservior, null))
                                p.SetValue(treservior, p.GetValue(t, null), null);
                        }



                    }
                }
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.success = false;
                Console.WriteLine(ex.Message);
            }

            return result;
        }

        public ApiResult GetDayRain()
        {
            ApiResult result = new ApiResult();
            HttpResponseParameter responseParameter1 = HttpUtil.Excute(new HttpRequestParameter
            {
                Url = "http://10.21.5.211:8080/lnflood/app/hydro/dayrain",
                IsPost = false,
                Encoding = Encoding.UTF8

            });
            result.success = true;
            try
            {
                var resarray = JsonConvert.DeserializeObject<raininfo>(responseParameter1.Body);
                var temp = resarray.data.Where(o =>
                {

                    if (string.IsNullOrEmpty(o.addvcd)) return false;
                    return o.addvcd.StartsWith("2111");
                });
              
                var conn = GetDBConn();

                //InsertBatch<dayrain>(conn, temp.ToList());
                foreach (var t in temp)
                {
                    //int count= Convert.ToInt32( Dapper.SqlMapper.ExecuteScalar(conn, "select count(*) from dayrain where stcd='"+t.stcd+"'"));

                    int count = _db.dayrain.Count(o => o.stcd == t.stcd);
                    if (count == 0)
                    {
                        _db.dayrain.Add(t);

                    }
                    else
                    {
                        //update
                       
                        var tdayrain = _db.dayrain.Single(r => r.stcd == t.stcd);
                        foreach (var p in _dayrainInfoCache)
                        {
                            if (p.Name == "id") continue;
                            if (p.GetValue(t, null) != p.GetValue(tdayrain, null))
                                p.SetValue(tdayrain, p.GetValue(t, null), null);
                        }



                    }
                }
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.success = false;
                Console.WriteLine(ex.Message);
            }

            return result;
        }



    }
}
